package com.rocksea.app.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rocksea.app.R;
import com.rocksea.app.adapter.DescrAdapter;
import com.rocksea.app.db.AskQueryPileTask;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.SonicWave.SonicWave;
import com.rocksea.app.db.StaticLoad.StaticLoad;
import com.rocksea.app.db.history.HistoryTable;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.db.lowStrain.LowStrainDb;
import com.rocksea.app.event.NotificationImage;
import com.rocksea.app.utils.PerUtils;
import com.rocksea.app.utils.UiUtils;
import com.rocksea.app.weight.OnRecyclerItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 吴志华 on 2017/10/17.
 *
 */

public class PileInfoActivity extends BaseAppCompatActivity
{

    public static final String INFO_EXTRA_KEY = "com.rocksea,app.PileInfoActivity.info";
    public static final String PILE_EXTRA_KEY = "com.rocksea,app.PileInfoActivity.pile";
    public static final String POSITION_EXTRA_KEY = "com.rocksea,app.PileInfoActivity.pile";

    private TextView mNoImageTip;
    private ListView pileInfoList;
    private RecyclerView pilePhotoList;
    private ArrayList<ImageTable> mImageTables;
    private PhotoAdapter adapter;
    private String[] infos;


    @Override
    protected void setContentView()
    {
        setContentView(R.layout.activity_pileinfo_layout);
    }
    @Override
    protected void initView()
    {
        EventBus.getDefault().register(this);
        mNoImageTip = (TextView) findViewById(R.id.No_Image);
        pileInfoList = (ListView) findViewById(R.id.Pile_Info);
        pilePhotoList = (RecyclerView) findViewById(R.id.Pile_Images);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
        pilePhotoList.setLayoutManager(gridLayoutManager);
        registerForContextMenu(pileInfoList);
        pilePhotoList.addOnItemTouchListener(new OnRecyclerItemClickListener(pilePhotoList)
        {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder)
            {
                Log.d("mRecyclerView", "onItemClick: ");
                Intent intent = new Intent(PileInfoActivity.this,PhotoViewActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList(PILE_EXTRA_KEY,mImageTables);
                intent.putExtra("111",bundle);
                intent.putExtra(POSITION_EXTRA_KEY,viewHolder.getPosition());
                startActivity(intent);
            }

            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder)
            {
                final int onLongClickPosition = viewHolder.getPosition();
                Log.d("mRecyclerView", "onLongClick: "+onLongClickPosition);
                AlertDialog.Builder builder = new AlertDialog.Builder(PileInfoActivity.this);
                builder.setTitle("删除");
                builder.setMessage("确定要删除这张照片吗");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                        String fileName = mImageTables.get(onLongClickPosition).getFileName();
                        long planId = mImageTables.get(onLongClickPosition).getPileId();
                        DbCenter.deleteImage(planId,fileName);
                        mImageTables.remove(onLongClickPosition);
                        adapter.notifyDataSetChanged();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                });
                builder.setCancelable(true);
                builder.show();
            }
        });
    }
    @Override
    protected void requrstAgin()
    {

    }
    @Override
    protected void initData()
    {
        loading();
        infos = getIntent().getStringArrayExtra(INFO_EXTRA_KEY);
        QueryPileTask mQueryPileTask = new QueryPileTask(infos[2]);
        mQueryPileTask.execute();
        AskQueryPileTask mAskQueryPileTask = new AskQueryPileTask(infos[0], infos[1],mOnAskQueryCallBack);
        mAskQueryPileTask.execute();
    }
    @Override
    protected void initBar(String title)
    {
        ActionBar mActionBar = getSupportActionBar();
        if (mActionBar!=null)
        {
            mActionBar.setTitle("桩基本信息");
            mActionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotificationImageList(NotificationImage notification)
    {
        switch (notification.getEventType())
        {
            case NotificationImage.DELETE:
                mImageTables.remove(notification.getPositon());
                adapter.notifyDataSetChanged();
                break;
            case NotificationImage.UPLOAD:
                mImageTables.get(notification.getPositon()).setUpLoadTime(10);
                adapter.notifyDataSetChanged();
                break;
        }
    }

    private AskQueryPileTask.OnAskQueryCallBack mOnAskQueryCallBack = new AskQueryPileTask.OnAskQueryCallBack()
    {
        @Override
        public void onError()
        {
            loadFailed();
        }

        @Override
        public void onSuccess(ArrayList<ImageTable> imageTables)
        {

            loadCompleted();
            if (imageTables.size()==0)
            {
                mNoImageTip.setVisibility(View.VISIBLE);
                return;
            }
            mImageTables = imageTables;
            adapter = new PhotoAdapter(PileInfoActivity.this,imageTables);
            pilePhotoList.setAdapter(adapter);
        }
    };
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private class PhotoAdapter extends RecyclerView.Adapter<PileInfoActivity.ViewHodler>
    {
        private Context context;
        private ArrayList<ImageTable> pilePhotos;
        private PhotoAdapter(Context context, ArrayList<ImageTable> pilePhotos)
        {
            this.context = context;
            this.pilePhotos = pilePhotos;
        }


        @Override
        public ViewHodler onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View item = LayoutInflater.from(context).inflate(R.layout.pile_photo_list_item_layout,parent,false);
            return new ViewHodler(item);
        }
        @Override
        public void onBindViewHolder(ViewHodler holder, int position)
        {
            Glide.with(context)
                    .load(new File(pilePhotos.get(position).getFilePath()))
                    .asBitmap()
                    .into(holder.pileImage);
            if (pilePhotos.get(position).getUpLoadTime()>0)
            {
                holder.pileImage.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary));
            }
        }

        @Override
        public int getItemCount()
        {
            return pilePhotos.size();
        }
    }

    private static class ViewHodler extends RecyclerView.ViewHolder
    {
        private ImageView pileImage;
        private ViewHodler(View itemView)
        {
            super(itemView);
            pileImage = (ImageView) itemView.findViewById(R.id.ImageView);
        }
    }

    private class QueryPileTask extends AsyncTask<Void,Void,String[]>
    {
        private String baseInfoId;
        private QueryPileTask(String baseInfoId)
        {
            this.baseInfoId = baseInfoId;
        }
        @Override
        protected String[] doInBackground(Void... params)
        {
            List<HistoryTable> historyTable = DbCenter.mHistoryDbHelper.queryByBaseInfoId(baseInfoId);
            if (historyTable==null||historyTable.size()==0)
                return new String[0];
            return dropInfoToArray(historyTable.get(0));
        }

        @Override
        protected void onPostExecute(String[] strings)
        {
            super.onPostExecute(strings);
            if (strings!=null)
            {
                DescrAdapter descrAdapter = new DescrAdapter(PileInfoActivity.this,strings);
                pileInfoList.setAdapter(descrAdapter);
            }
            else
                UiUtils.showToast("获取数据失败");
        }
    }
    public static final String LABLE = " ";
    private String[] dropInfoToArray(HistoryTable historyTable)
    {
        ArrayList<String> infos = new ArrayList<>();
        switch (historyTable.getType())
        {
            case HistoryTable.TEST_DY:
                LowStrainDb mLowStrain = DbCenter.mDyDbHelper.queryByBaseInfoId(historyTable.BaseInfoId);
                if (mLowStrain!=null)
                {
                    commonOption(historyTable, infos);
                    infos.add(String.format("桩长%s%s",LABLE,String.valueOf(mLowStrain.pileLength)));
                    infos.add(String.format("桩径%s%s",LABLE,String.valueOf(mLowStrain.pileDiameter)));
                    infos.add(String.format("通道数%s%s",LABLE,String.valueOf(mLowStrain.validDataCount)));
                }
                break;
            case HistoryTable.TEST_GY:
                break;
            case HistoryTable.TEST_JZ:
                StaticLoad mStaticLoad = DbCenter.mStaticLoadDbHelper.queryById(historyTable.BaseInfoId);
                if (mStaticLoad!=null)
                {
                    commonOption(historyTable, infos);

                    infos.add(String.format("设计载荷%s%s",LABLE,String.valueOf(mStaticLoad.maxLoad)));
                    infos.add(String.format("分级数%s%s",LABLE,String.valueOf(mStaticLoad.preSeries)));
                    infos.add(String.format("测试规范%s%s",LABLE,mStaticLoad.standard));
                }
                break;
            case HistoryTable.TEST_SC:
                SonicWave mSonicWave = DbCenter.mScDbHelper.queryByBaseInfoId(historyTable.BaseInfoId);
                if (mSonicWave!=null)
                {
                    commonOption(historyTable, infos);
                    infos.add(String.format("桩长%s%s",LABLE,String.valueOf(mSonicWave.pileLength)));
                    infos.add(String.format("桩径%s%s",LABLE,String.valueOf(mSonicWave.pileDiameter)));
                    infos.add(String.format("剖面数%s%s",LABLE,String.valueOf(mSonicWave.sectionCount)));
                }
                break;
            default:
                break;
        }
        if (infos.size()==0)
            return null;
        else
        {
            String[] infoArrays = new String[infos.size()];
            for (int i = 0; i < infos.size(); i++)
            {
                infoArrays[i] = infos.get(i);

            }
            return infoArrays;
        }
    }
    private void commonOption(HistoryTable historyTable, ArrayList<String> infos) {
        infos.add(String.format("流水号%s%s",LABLE,historyTable.getSerialNo()));
        infos.add(String.format("桩号%s%s",LABLE,historyTable.getPileNo()));
        infos.add(String.format("测试时间%s%s",LABLE, PerUtils.dateToStr(new Date(historyTable.CreatTime))));
        if (historyTable.getIsLoad()==0)
        {
            infos.add(String.format("上传时间%s%s",LABLE,"未上传"));
        }
        else
        {
            infos.add(String.format("上传时间%s%s",LABLE,PerUtils.dateToStr(new Date(historyTable.LoadTime))));
        }
    }
}
